package com.nami.logic.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.ObjectUtil;
import com.nami.gate.api.request.message.DownMsgBatchReq;
import com.nami.gate.api.request.message.DownMsgRequest;
import com.nami.gate.api.service.RemoteDownMsgRecvService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.rpc.cluster.specifyaddress.Address;
import org.apache.dubbo.rpc.cluster.specifyaddress.UserSpecifiedAddressUtil;
import org.dromara.common.core.utils.StringUtils;

/**
 * 系统转发消息util
 *
 * @Author: lbc
 * @Date: 2023-08-18 18:48
 * @email: 594599620@qq.com
 * @Description: keep coding
 */
@Slf4j
public class ForwardPacketUtil {

    /**
     * 向长连接节点发送单体消息
     *
     * @param request
     * @param dubboIp
     * @param dubboPort
     * @return
     */
    public static boolean flushPacket(DownMsgRequest request, String dubboIp, Integer dubboPort) {
        log.info("[TransferPacketUtil] 推送消息至长连接节点【{}:{}】。client:[{}]", dubboIp, dubboPort, request.getIdentityNo());
        if (ObjectUtil.isNull(request) || StringUtils.isBlank(dubboIp)
            || null == dubboPort || StringUtils.isBlank(request.getIdentityNo())) {
            log.warn("[TransferPacketUtil] 发送消息失败，丢失核心参数：id:{}, user:{}", request.getMessageId(), request.getIdentityNo());
            return Boolean.FALSE;
        }
        // 调用绑定得长连接服务器
        ReferenceConfig<RemoteDownMsgRecvService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setInterface(RemoteDownMsgRecvService.class);
        RemoteDownMsgRecvService downMsgRecvService = referenceConfig.get();
        UserSpecifiedAddressUtil.setAddress(new Address(dubboIp, dubboPort, true));
        return downMsgRecvService.flushChannel(request);
    }

    /**
     * 向长连接节点发送批量消息
     * 时间有点长 400ms
     *
     * @param dto
     * @param dubboIp
     * @param dubboPort
     * @return
     */
    public static void flushMore(DownMsgBatchReq dto, String dubboIp, Integer dubboPort) {
        TimeInterval timer = DateUtil.timer();
        log.info("[TransferPacketUtil] 推送批量消息至长连接节点【{}:{}】，size：{}", dubboIp, dubboPort, dto.getIdentityNos().size());
        // 调用绑定得长连接服务器
        ReferenceConfig<RemoteDownMsgRecvService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setInterface(RemoteDownMsgRecvService.class);
        RemoteDownMsgRecvService messageChannelManager = referenceConfig.get();

        UserSpecifiedAddressUtil.setAddress(new Address(dubboIp, dubboPort, true));
        messageChannelManager.flushMore(dto);
        if (timer.interval() > 500) {
            log.warn("[TransferPacketUtil] 调用出现问题，生产者消费不过来了。。==！ use:{}ms", timer.interval());
        }

    }

}
